package com.example.yls.demob;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.net.URI;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements delStudent{
    private ListView stuListView;
    private Button btn_AddStu;
    private ArrayList<Student> studentArrayList=new ArrayList<>();
    private MyAdapter myAdapter;
    private Button query_stu;
    private static final String TAG = "MainActivity";
    private EditText edit_searchstu;
    private Button btn_searchstu;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBundler();
        myAdapter=new MyAdapter(studentArrayList,MainActivity.this,MainActivity.this);
        stuListView.setAdapter(myAdapter);
        query_stuEvent();
        btn_AddStuEvent();
        stuListViewItemEvent();
        readDataFromDB();
        /*
        搜索框的内容变化监听
        *
        * */
        edit_searchstu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                                 String search=edit_searchstu.getText().toString();
                                    readMDataFromDB(search);
            }
        });

    }
    /*
        列表各个项目的点击事件
    * */
    private void stuListViewItemEvent() {
                  stuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                      @Override
                      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                          Intent intent =new Intent();
                          intent.setClass(MainActivity.this, EditStuActivity.class);
                          Student student=studentArrayList.get(i);
                          intent.putExtra("STUNO",student.getStuno());
                          intent.putExtra("NAME",student.getName());
                          intent.putExtra("AGE",student.getAge());
                          intent.putExtra("SEX",student.getSex());
                          startActivityForResult(intent,3000);
                      }
                  });
    }


    /*   接收intent的返回    */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==2001){
            String stuno=data.getStringExtra("STUNO");
            String name=data.getStringExtra("NAME");
            int age=data.getIntExtra("AGE",0);
            String sex=data.getStringExtra("SEX");
            Student student=new Student(stuno,name,age,sex);
            insertStuToDB(student);
            readDataFromDB();
        }
        else if (resultCode==3001){
            String stuno=data.getStringExtra("STUNO");
            String name=data.getStringExtra("NAME");
            int age=data.getIntExtra("AGE",0);
            String sex=data.getStringExtra("SEX");
            Student student=new Student(stuno,name,age,sex);
            UpdataToDB(student);
            readDataFromDB();
        }
    }

    /*
    *   更新数据方法；
    * */

    private void UpdataToDB(Student student) {
        Uri uri=Uri.parse("content://com.sql/student");
                     ContentValues values=new ContentValues();
                     values.put("stuno",student.getStuno());
                     values.put("name",student.getName());
                     values.put("age",student.getAge());
                     values.put("sex",student.getSex());
                     String where="stuno="+student.getStuno();
                     getContentResolver().update(uri,values,where,null);
    }
/*        插入数据方法；
*                                 */
    private void insertStuToDB(Student student) {
        Uri uri=Uri.parse("content://com.sql/student");
                       String stuno=student.getStuno();
                       String name=student.getName();
                       int age=student.getAge();
                       String sex=student.getSex();
                       ContentValues values=new ContentValues();
                       values.put("STUNO",stuno);
                       values.put("NAME",name);
                       values.put("AGE",age);
                       values.put("SEX",sex);
                       getContentResolver().insert(uri,values);
    }
                        /*   添加按钮的点击事件，添加学生
                        *
                        * */
    private void btn_AddStuEvent() {
                          btn_AddStu.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View view) {
                                  Intent intent=new Intent();
                                  intent.setClass(MainActivity.this,AddStuActivity.class);
                                  startActivityForResult(intent,2000);
                              }
                          });
    }

       /*   查询按钮的点击事件，查询学生
       * */
    private void query_stuEvent() {

          query_stu.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                readDataFromDB();
              }
          });
    }
/*
*           查询学生的方法；
*
* */
    private void readDataFromDB(){
        String name;
        String stuno;
        int age;
        String sex;
        Uri uri=Uri.parse("content://com.sql/student");
        Cursor cursor=getContentResolver().query(uri,null,null,null,null);
        studentArrayList.clear();
        if (cursor!=null&&cursor.getCount()!=0) {
            for (cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext()) {
                 stuno = cursor.getString(0);
                 name = cursor.getString(1);
                 age = cursor.getInt(2);
                 sex=cursor.getString(3);
                Student student = new Student(stuno, name, age,sex);
                studentArrayList.add(student);
            }
        }
   /*     Log.e(TAG, "readDataFromDB:"+cursor.getCount() );*/
        myAdapter.notifyDataSetChanged();
    }

    private void readMDataFromDB(String search){
        String name;
        String stuno;
        int age;
        String sex;
        Uri uri=Uri.parse("content://com.sql/student");
        String selection="stuno like '%"+search+"%'"+"or name like '%"+search+"%' "+"or age='"+search+"'";
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        studentArrayList.clear();
        if (cursor!=null&&cursor.getCount()!=0) {
            for (cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext()) {
                stuno = cursor.getString(0);
                name = cursor.getString(1);
                age = cursor.getInt(2);
                sex=cursor.getString(3);
                Student student = new Student(stuno, name, age,sex);
                studentArrayList.add(student);
            }
        }
    /*    Log.e(TAG, "readDataFromDB:"+cursor.getCount() );*/
        myAdapter.notifyDataSetChanged();
    }

                 /*     初始化各种绑件标签   */
    private void initBundler() {
                       stuListView=findViewById(R.id.stu_list);
                       query_stu=findViewById(R.id.query_stu);
                       btn_AddStu=findViewById(R.id.addstu_main);
                       edit_searchstu=findViewById(R.id.edit_searchstu);
                       btn_searchstu=findViewById(R.id.btn_searchstu);
    }
    @Override
    public void del_student(Student student) {
                    Uri uri=Uri.parse("content://com.sql/student");
                    String where="stuno="+student.getStuno();
                    getContentResolver().delete(uri,where,null);
                    readDataFromDB();
      }
}
